package com.example.core.adapter;

import org.jgroups.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class SysReceiverAdapter extends ReceiverAdapter {

    Logger logger = LoggerFactory.getLogger(getClass());

    private View view = null;

    @Override
    public void receive(Message message) {
        logger.warn("节点收到消息：" + message.getObject());
    }

    @Override
    public void viewAccepted(View view) {
        if (this.view == null) {
            //集群开始初始化
            logger.warn("集群刚初始化，本节点加入到集群...");
        } else {
            List<Address> leftMembers = View.leftMembers(this.view, view);
            List<Address> joinedMembers = View.newMembers(this.view, view);
            if (this.view.getMembers().size() > view.getMembers().size()) {
                //有节点掉线了
                if (!leftMembers.isEmpty()) {
                    for (Address address : leftMembers) {
                        logger.warn("节点: {} 已离开到集群...", address.toString());
                    }
                }
            } else {
                //有节点上线了
                if (!joinedMembers.isEmpty()) {
                    for (Address address : joinedMembers) {
                        logger.warn("节点: {} 已加入到集群...", address.toString());
                    }
                }
            }
        }
        this.view = view;
    }
}
